const charset = require('superagent-charset');
const superagent =  charset(require('superagent'));
require('superagent-proxy')(superagent);

const {
    readTask,
} = require('./ti_logic_read_task');

const {
    logger,
    sleep,
} = require('./util');

const fs = require('fs');


process.on('unhandledRejection', error => {
    //...不处理...
});

let openSerials = [];//需要关注的规格

//每N秒重新拉取任务列表
(async () => {
    while (1) {
        const tasks = await readTask();
        if (!tasks) continue;
        const tmpOpenSerials = [];
        for (const task of tasks) {
            if (task.status != 1) continue;
            tmpOpenSerials.push(task.serial);
        }
        openSerials = tmpOpenSerials;

        await sleep(30000);
    }
})();

const tiPost = (url, data, contentType, cookie, referer) => {
	return new Promise((resolve, reject) => {
		superagent.post(url).timeout(30000)
			.set('Host', 'www.ti.com.cn')
			.set('Connection', 'keep-alive')
			.set('sec-ch-ua', '"Google Chrome";v="95", "Chromium";v="95", ";Not A Brand";v="99"')
			.set('sec-ch-ua-mobile', '?0')
			.set('user-agent','Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.54 Safari/537.36')
			.set('Content-Type', contentType)
			.set('X-Sec-Clge-Req-Type', 'ajax')
            .set('X-Requested-With', 'XMLHttpRequest')
			.set('Expires', '0')
			.set('Cache-Control', 'no-store, must-revalidate')
			.set('sec-ch-ua-platform', '"macOS"')
			.set('Accept', '*/*')
			.set('Origin', 'https://www.ti.com.cn')
			.set('Sec-Fetch-Site', 'same-origin')
			.set('Sec-Fetch-Mode', 'cors')
			.set('Sec-Fetch-Dest', 'empty')
			.set('Referer', referer)
			.set('Accept-Encoding', 'gzip, deflate, br')
			.set('Accept-Language', 'zh-CN,zh;q=0.9,en;q=0.8')
			.set('Cookie', cookie)
			.send(data)
			.end((err, res) => {
				if (err) {
					return reject(err);
				}
				resolve(res.text);
			});
	});
}

const httpPost = (url, data) => {
	return new Promise((resolve, reject) => {
		superagent.post(url).timeout(20000)
			.set('user-agent','Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.54 Safari/537.36')
			.set('content-type','application/json')
			.send(data)
			.end((err, res) => {
				if (err) {
					return reject(err);
				}
				resolve(res.text);
			});
	});
}

const readCookieFromFile = () => {
    return new Promise((resolve, reject) => {
        fs.readFile('cookie.txt', 'utf-8', (err, data) => {
            if (err) {
                reject(err);
            } else {
                if (data.indexOf('Cookie:') === 0) {
                    data = data.substr(7).trim();
                }
                resolve(data);
            }
        });
    });
}

//每1小时只通知一次
const recentNotify = {};

(async () => {
    const url = 'https://www.ti.com.cn/storeservices/cart/inventory';
    const referer = 'https://www.ti.com.cn/ordering-resources/buying-tools/quick-add-to-cart.html';

    while (1) {
        try {
            if (openSerials.length == 0) {
                await sleep(1000);
                continue;
            }
            const g_cookie = await readCookieFromFile();
            const postData = JSON.stringify(openSerials);

            logger('查询库存...', postData);
            const retStr = await tiPost(url, postData, 'application/json', g_cookie, referer);
            logger('retStr', retStr);
            const retJson = JSON.parse(retStr);
            for (const v of retJson.opn_list) {
                if (v.quantity > 0 && v.purchase_flag == 'Y') {
                    if (recentNotify[v.orderable_number] && (new Date().getTime()) - recentNotify[v.orderable_number] < 3600000) {
                        continue;
                    }
                    recentNotify[v.orderable_number] = new Date().getTime();

                    const msg = `规格 ${v.orderable_number} 有 ${v.quantity} 库存可以下单`;
                    logger(msg);
                    //推送消息
                    await httpPost('http://wxpusher.zjiecode.com/api/send/message', JSON.stringify({
                        appToken: 'AT_XGmRz8RFSZBtLyaYBx52r8YziWCSrbEg',
                        content: msg,
                        contentType: 1,
                        uids: [
                            'UID_ICAsgfMbgOLiDal8Zs6IYs3cF1pn',
                            'UID_n1quSUwrZ0QRNkITxOeH54bYSEbK',
                            'UID_e2EvnkezKPxdnQvDBPv11sdWYno3',
                        ]
                    }));
                }
            }
        } catch(e) {
            logger('查询失败', e);
        }
        
        await sleep(60000);
    }

})();


/*
(async () => {
    console.log('ABC')
    const msg = `规格 ABC 有 12345 库存可以下单`;
    const ret = await httpPost('http://wxpusher.zjiecode.com/api/send/message', JSON.stringify({
        appToken: 'AT_XGmRz8RFSZBtLyaYBx52r8YziWCSrbEg',
        content: msg,
        contentType: 1,
        uids: [
            'UID_ICAsgfMbgOLiDal8Zs6IYs3cF1pn',
            'UID_e2EvnkezKPxdnQvDBPv11sdWYno3',
        ]
    }));
    console.log('ret', ret)
})();
*/

